package cn.bdqn.controller.sys;

import cn.bdqn.entity.SwiperImage;
import cn.bdqn.service.sys.SysSwiperService;
import cn.bdqn.utils.MyLog;
import cn.bdqn.utils.StaticUrl;
import cn.bdqn.utils.UploadFile;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.ueditor.ActionEnter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: ycbdqn
 * @Package: cn.bdqn.controller.sys
 * @Author: huat
 * @Date: 2020/3/10 14:22
 * @Version: 1.0
 */
@Controller
@RequestMapping("sys/swiper")
public class SwiperController {
    @Autowired
    SysSwiperService sysSwiperService;
    /**
     * 进入轮播图页面
     * @return
     */
    @RequestMapping("intoSwiper")
    public String intoSwiper(){
        return "swiper/swiper";
    }

    @RequestMapping("intoUpdateSwiper")
    public String intoUpdateSwiper(int id, Model model){
        model.addAttribute("swiper",sysSwiperService.getSwiperImageById(id));
        return "swiper/updateSwiper";
    }

    /**
     * 查询轮播图
     * @param page 起始位置
     * @param limit 页面大小
     * @param swiperName    轮播图名称
     * @return
     */
    @RequestMapping("getAllSwiper")
    @ResponseBody
    @MyLog("获取轮播图")
    public Map<String,Object> getAllSwiper(int page,int limit,String swiperName){

        return sysSwiperService.getAllSwiper(page, limit, swiperName);
    }

    /**
     * 根据id删除轮播图
     * @param swiperId 轮播图id
     * @return
     */
    @RequestMapping("deleteSwiper")
    @ResponseBody
    @MyLog("删除轮播图")
    public boolean deleteSwiper(int swiperId){
        return sysSwiperService.deleteSwiper(swiperId);
    }

    @Value("${route_name}")
    private String routeName;//获取图片前面路径

    /**
     * 富文本编辑器上传图片
     * @param action
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("config")
    public Object config(String action,HttpServletRequest request,HttpServletResponse response) throws IOException {
        if(action.equals("uploadimage")){
            Map<String,Object> map=new HashMap<String,Object>();
           try{

               String path=UploadFile.getFileURL(((MultipartHttpServletRequest)request),"upfile");
               map.put("url",path);
               map.put("state","SUCCESS");
               PrintWriter writer = response.getWriter();
               writer.print(JSONObject.toJSONString(map));
               writer.flush();;
               writer.close();
           }catch (Exception e){
               e.printStackTrace();
               map.put("state","上传失败");
           }
            return null;
        }
        return "redirect:/webapp/ueditor/jsp/config.json";
    }

    /**
     * 根据id修改轮播图
     * @param swiperImage
     * @return
     */
    @RequestMapping("updateSwiperById")
    @ResponseBody
    @MyLog("修改轮播图")
    public String updateSwiperById(HttpServletRequest request,SwiperImage swiperImage){
        MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;

        if(null!=mr.getMultiFileMap().get("img")){
            String fileName=mr.getFileMap().get("img").getOriginalFilename();
            String fileNameIsJPG=fileName.substring(fileName.lastIndexOf(".")+1);
            if(!"jpg".equalsIgnoreCase(fileNameIsJPG)){
                return "2";
            }
            String result= UploadFile.getFileURL(mr,"img");

            swiperImage.setImageUrl(routeName+"/image/"+result);
        }
        return sysSwiperService.updateSwiperById(swiperImage);

    }

    /**
     * 进入添加页面
     * @return
     */
    @RequestMapping("intoAddSwiper")
    public String intoAddSwiper(){
        return "swiper/addSwiper";
    }

    /**
     * 添加轮播图
     * @param swiperImage
     * @param bindingResult
     * @param mr
     * @return
     */
    @RequestMapping("addSwiper")
    @ResponseBody
    @MyLog("新增轮播图")
    public Object addSwiper(@Valid SwiperImage swiperImage, BindingResult bindingResult,MultipartHttpServletRequest mr){
        List<ObjectError> error=null;
        //返回boolean 是为了验证@Validated后面bean 里是否有不符合注解条件的错误信息
        if(bindingResult.hasErrors()){
            //获得所有错误信息返回list集合
            error=bindingResult.getAllErrors();
            for (ObjectError o:error) {
                //获得不符合要求的message
                return JSON.toJSONString(o.getDefaultMessage());
            }

        }
        if(null!=mr.getMultiFileMap().get("img")){
            String fileName=mr.getFileMap().get("img").getOriginalFilename();
            String fileNameIsJPG=fileName.substring(fileName.lastIndexOf(".")+1);
            if(!"jpg".equalsIgnoreCase(fileNameIsJPG)){
                return "2";
            }
            String result= UploadFile.getFileURL(mr,"img");

            swiperImage.setImageUrl(routeName+"/image/"+result);
            return sysSwiperService.addSwiper(swiperImage);
        }else{
            return "2";
        }

    }
    @RequestMapping("selectSwiper")
    @MyLog("查看轮播图")
    public String selectSwiper(int id,Model model){
       SwiperImage swiperImage= sysSwiperService.getSwiperImageById(id);
       model.addAttribute("swiper",swiperImage);
        return "swiper/selectSwiper";
    }
}
